import {Component, ViewChild} from '@angular/core';
import {Platform, IonicApp, Nav, ToastController, Keyboard} from 'ionic-angular';
import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';

import {TabsPage} from '../pages/tabs/tabs';
import {Helper} from "../common/Helper";
import {LoginPage} from "../pages/login/login";

@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  @ViewChild('myNav') nav: Nav
  rootPage: any = TabsPage
  backButtonPressed: boolean = false
  backButtonCanUse: boolean = true

  constructor(public platform: Platform,
              public ionicApp: IonicApp,
              public keyboard: Keyboard,
              public statusBar: StatusBar,
              public toastCtrl: ToastController,
              public splashScreen: SplashScreen) {
    if (this.platform.is('android')) {
      //不要放在ready下执行  导致布局 取值不及时
      document.body.classList.add('g-body-md')
    }
    platform.ready().then(() => {
      if (this.platform.is('android')) {
        this.statusBar.hide()
      } else {
        this.statusBar.styleDefault()
      }
      this.splashScreen.hide()

      Helper.eventManage.emit('app/setBackButtonAction')
    });

    Helper.eventManage.on('app/setBackButtonAction',()=>{
      this.registerBackButtonAction()
    })

    Helper.eventManage.on('user/gotoLogin',()=>{
      this.nav.push(LoginPage)
    })

  }

  registerBackButtonAction() {
    this.platform.registerBackButtonAction(() => {
      if (!this.backButtonCanUse) return
      this.backButtonCanUse = false
      setTimeout(()=>{
        this.backButtonCanUse = true
      },500)
      if (this.keyboard.isOpen()) {
        this.keyboard.close()
        return
      }
      //如果想点击返回按钮隐藏toast或loading或Overlay就把下面加上
      // this.ionicApp._toastPortal.getActive() || this.ionicApp._loadingPortal.getActive() ||
      let activePortal = this.ionicApp._modalPortal.getActive() || this.ionicApp._overlayPortal.getActive()
      if (activePortal) {
        activePortal.dismiss().catch(() => {
        });
        activePortal.onDidDismiss(() => {
        });
        return;
      }
      let activeVC = this.nav.getActive();
      let tabs = activeVC.instance.tabRef;
      let activeNav = tabs.getSelected();
      return activeNav.canGoBack() ? activeNav.pop() : this.showExit()
    }, 1);
  }

  //双击退出提示框
  showExit() {
    if (this.backButtonPressed) { //当触发标志为true时，即2秒内双击返回按键则退出APP
      this.platform.exitApp();
    } else {
      this.toastCtrl.create({
        message: '再按一次退出应用',
        duration: 2000,
        position: 'middle'
      }).present();
      this.backButtonPressed = true;
      setTimeout(() => this.backButtonPressed = false, 2000);//2秒内没有再次点击返回则将触发标志标记为false
    }
  }

}
